package com.jyw.router.hospital.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson2.JSON;
import com.jyw.router.common.exception.ServiceException;
import com.jyw.router.common.utils.StringUtils;
import com.jyw.router.hospital.domain.WxUser;
import com.jyw.router.hospital.domain.vo.WxSendInputVo;
import com.jyw.router.hospital.service.IWxService;
import com.jyw.router.hospital.service.IWxUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.jyw.router.common.constant.WxTemplateConstant.*;


/**
 * @author 沈峻
 * @ClassName WxServiceImpl
 * @Description TODO
 * @Date 2023/4/24 14:22
 **/
@Service
@Slf4j(topic = "微信消息推送")
@AllArgsConstructor
public class WxServiceImpl implements IWxService {

    private final WxMpService wxMpService;

    private final WxMaService wxMaService;

    @Resource
    private IWxUserService wxUserService;

    @Resource
    private ConfigurableApplicationContext context;

    private void setTemplate(WxSendInputVo vo,String template){
        String code = context.getEnvironment().getProperty("wx.mp.template."+template+".code");
        String page = context.getEnvironment().getProperty("wx.mp.template."+template+".page");
        if(!StringUtils.isEmpty(code)&&StringUtils.isEmpty(vo.getCode())){
            vo.setCode(code);
        }
        if(!StringUtils.isEmpty(page)&&StringUtils.isEmpty(vo.getPage())){
            vo.setPage(page);
        }
    }

    @Override
    public void transferTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送转单通知");
        setTemplate(wxSendInputVo,TRANSFER);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void assignTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送派单通知");
        setTemplate(wxSendInputVo,ASSIGN);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void makeTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送工单处理通知");
        setTemplate(wxSendInputVo,MAKE);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void createOrderTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送工单受理通知");
        setTemplate(wxSendInputVo,CREATE_ORDER);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void assistTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送派单通知");
        setTemplate(wxSendInputVo,ASSSIT);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void itemTimeoutTemplate(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送超时通知");
        setTemplate(wxSendInputVo,TIMEOUT);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void scheduleMsg(WxSendInputVo wxSendInputVo) {
        log.info("@微信推送消息:发送排班通知");
        setTemplate(wxSendInputVo,TIMEOUT);
        sendMessage(wxSendInputVo);
    }

    @Override
    public void sendMessage(WxSendInputVo wxSendInputVo){
        if(StringUtils.isEmpty(wxSendInputVo.getUsers())){
            throw new ServiceException("用户不能为空");
        }
        Arrays.stream(wxSendInputVo.getUsers().split(",")).forEach(data->{
            //通过用户手机号获取用户信息
            WxUser wxUser = wxUserService.getUserByPhone(data);
            if(ObjectUtils.isEmpty(wxUser)){
                log.warn("用户:{},未在微信中注册,发送消息失败",data);
                return;
            }
            if(wxUser.getSubscribe().equals(0)){
                log.warn("用户:{},未关注公众号,发送消息失败",data);
                return;
            }
            if(StringUtils.isEmpty(wxUser.getMpOpentId())){
                log.warn("用户:{},找不到公众号唯一标识,发送消息失败",data);
                return;
            }
            WxMpTemplateMessage message = new WxMpTemplateMessage();
            message.setTemplateId(wxSendInputVo.getCode());
            message.setToUser(wxUser.getMpOpentId());
            if(!ObjectUtils.isEmpty(wxSendInputVo.getData())){
                Map<String,Map<String,String>> dataMap = (Map<String, Map<String, String>>) wxSendInputVo.getData();
                Set<String> keySet = dataMap.keySet();
                List<WxMpTemplateData> templateDataList = keySet.stream().map(dataKey -> {
                    WxMpTemplateData templateData = new WxMpTemplateData();
                    templateData.setName(dataKey);
                    templateData.setValue(dataMap.get(dataKey).get("value"));
                    templateData.setColor(dataMap.get(dataKey).get("color"));
                    return templateData;
                }).collect(Collectors.toList());
                message.setData(templateDataList);
            }
            message.setMiniProgram(new WxMpTemplateMessage.MiniProgram(){{
                setAppid(wxMaService.getWxMaConfig().getAppid());
                if(!StringUtils.isEmpty(wxSendInputVo.getPage())){
                    setPagePath(wxSendInputVo.getPage());
                    if(!StringUtils.isEmpty(wxSendInputVo.getPageData())){
                        setPagePath(getPagePath()+wxSendInputVo.getPageData());
                    }
                }
            }});
            log.info("@微信推送消息,请求消息体:{}",message);
            try {
                String result = wxMpService.getTemplateMsgService().sendTemplateMsg(message);
                log.info("@微信推送消息,返回消息:{}",result);
            } catch (WxErrorException e) {
                log.error("@微信推送消息,发生异常",e);
            }
        });

    }

}
